package com.fangda.network.websocket.client;

import com.fangda.network.*;
import com.fangda.network.websocket.AbstractWebsocketNetwork;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocketBase;
import lombok.Getter;
import lombok.Setter;

public class WebsocketClientNetwork extends AbstractWebsocketNetwork {

    @Getter
    @Setter
    private HttpClient httpClient;

    @Getter
    protected WebSocketBase websocket;



    public WebsocketClientNetwork(String id, NetworkConfig config) {
        super(id, config);
    }

    public void connect() {
        httpClient.webSocket(config.getPort(), config.getIp(), config.getPath(), result -> {
            if(result.succeeded()) {
                setAlive(true);
                websocket = result.result();
                initWebsocket();
            } else {
                setAlive(false);
            }
            if(callback != null) {
                callback.connectionChange(result.succeeded(), null);
            }
        });
    }

    @Override
    public NetworkType getNetworkType() {
        return NetworkType.WEBSOCKET_CLIENT;
    }

    @Override
    public void shutdown() {
        if(httpClient != null) {
            httpClient.close(r -> {
                setAlive(!r.succeeded());
                if(callback != null) {
                    callback.connectionChange(false, null);
                }
            });
        } else {
            setAlive(false);
        }
    }

    @Override
    public void reload() {
        shutdown();
        connect();
    }

    public void send(NetworkMessage message, NetworkMessageCallback messageCallback) {
        websocket.writeBinaryMessage(Buffer.buffer(message.getPayload()), res -> {
            messageCallback.callback(res, websocket.remoteAddress());
        });
    }

    protected void initWebsocket() {
        websocket.handler(r -> {//收数据
            if(config.getParser() != null) {
                config.getParser().decode(new NetworkMessage(r.getBytes(), websocket.remoteAddress().toString()));
            }
        });
        websocket.closeHandler( r -> {//关闭数据
            setAlive(false);
        });
        websocket.exceptionHandler(v -> {
            if(getCallback() != null) {
                getCallback().exceptionHandler(v);
            }
        });
    }

}
